package com.flower8.service.impl;

import com.flower8.dao.SysMenuDao;
import com.flower8.model.SysMenu;
import com.flower8.service.SysLogService;
import com.flower8.service.SysMenuService;
import com.flower8.utils.SpringUtil;
import com.flower8.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 菜单service实现类
 * @Author: tanglin
 * @Date: 2019/09/04 16:05
 * @Version: 1.0
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuDao sysMenuDao;
    /**
     * 根据主键查询菜单
     * @param id 菜单主键id
     * @return
     */
    @Override
    public SysMenu getById(Long id) {
        return sysMenuDao.getById(id);
    }

    /**
     * 查询所有菜单
     *
     * @return
     */
    @Override
    public List<SysMenu> getMenuAll() {
        return sysMenuDao.getMenuAll();
    }

    /**
     * 查看用户权限内的菜单
     * @param permission 权限内的菜单字符串
     * @return
     */
    @Override
    public List<SysMenu> getListByUser(String permission) {
        List<SysMenu> menuList = new ArrayList();
        Map param = new HashMap<>();
        if(permission == null || "".equals(permission)){
            return null;
        }
        if (permission != null) {
            if (permission.equals("all")) {
                param.put("permiArray",null);
                menuList = sysMenuDao.getListByUser( param);
            }else{
                String[] permiArray = permission.split(",");
                param.put("permiArray",permiArray);
                menuList = sysMenuDao.getListByUser(param);
            }
        }
        return menuList;
    }

    /**
     * 更新菜单
     * @param sysMenu
     */
    @Override
    @Transactional
    public void updateMenu(SysMenu sysMenu) {
        sysMenuDao.updateMenu(sysMenu);
        SpringUtil.getBean(SysLogService.class).save(UserUtil.getCurrentUser().getId(), "修改菜单", UserUtil.getCurrentUser().getAccount()+"修改菜单");
    }

    /**
     * 新增菜单
     * @param sysMenu
     */
    @Override
    public void saveMenu(SysMenu sysMenu) {
        sysMenuDao.saveMenu(sysMenu);
        SpringUtil.getBean(SysLogService.class).save(UserUtil.getCurrentUser().getId(), "新增菜单", UserUtil.getCurrentUser().getAccount()+"新增菜单");
    }

    /**
     * 删除菜单
     * @param id
     */
    @Override
    public void deleteMenu(Long id)throws Exception {
        sysMenuDao.deleteMenu(id);
        SpringUtil.getBean(SysLogService.class).save(UserUtil.getCurrentUser().getId(), "删除id为"+id+"的菜单", UserUtil.getCurrentUser().getAccount()+"删除菜单");
    }

    /**
     * 查询一级菜单
     *
     * @return
     */
    @Override
    public List<SysMenu> listParents() {
        return sysMenuDao.listParents();
    }
}
